package com.sheeran.aichat.feign;

import cn.hutool.json.JSONUtil;
import com.sheeran.aichat.dto.common.rest.WrappedResponse;
import com.sheeran.aichat.exception.BusinessException;
import feign.FeignException;
import feign.Response;
import feign.codec.Decoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestClientException;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author: sheeran
 * @create: 2025/02/10
 */
@RequiredArgsConstructor
@Slf4j
public class WrappedResponseExceptionDecoder implements Decoder {

    private final Decoder defaultDecoder;

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        try {
            return defaultDecoder.decode(response, type);
        } catch (RestClientException e) {
            log.error(e.getMessage(), e);

            String json = response.body().toString();
            WrappedResponse<?> jsonRes = JSONUtil.toBean(json, WrappedResponse.class);
            if (!jsonRes.isSuccess()) {
                String message = (String) jsonRes.getResult();
                throw new BusinessException(jsonRes.getCode(), jsonRes.getMsg(), message);
            }

            return null;
        }
    }
}
